
package com.android.fitnesscenter.view.server;

import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.ConfigProperties.QueryDetailResult;
import com.android.fitnesscenter.utils.ConfigProperties.TradingType;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.MapEntity;
import com.android.fitnesscenter.utils.TimerHelper;
import com.android.fitnesscenter.utils.ToastHelper;
import com.android.fitnesscenter.utils.ViewHelper;
import com.android.fitnesscenter.view.BaseActivity;
import com.android.fitnesscenter.widget.CustomDatePickerDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class ServerModifyDetailActivity extends BaseActivity {

    private MapEntity entity;

    @ViewInject(R.id.txt_old_user)
    private TextView txt_old_user;

    @ViewInject(R.id.txt_old_type)
    private TextView txt_old_type;

    @ViewInject(R.id.txt_old_time)
    private TextView txt_old_time;

    @ViewInject(R.id.txt_old_money)
    private TextView txt_old_money;

    @ViewInject(R.id.txt_new_user)
    private TextView txt_new_user;

    @ViewInject(R.id.txt_new_type)
    private TextView txt_new_type;

    @ViewInject(R.id.txt_new_time)
    private TextView txt_new_time;

    @ViewInject(R.id.edtxt_new_money)
    private EditText edtxt_new_money;

    @ViewInject(R.id.btn_ok)
    private Button btn_ok;
    private String type = TradingType.PAY;
    private String username = "";
    private String id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_modify_detail_layout);
        ViewUtils.inject(this);
        initTitleBar(getString(R.string.txt_modify_detail));
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            entity = (MapEntity) bundle.getSerializable("entity");
        }
        username = entity.getString(QueryDetailResult.USER_NAME);
        type = entity.getString(QueryDetailResult.TYPE);
        String operate_money = entity.getString(QueryDetailResult.MONEY);
        String time = entity.getString(QueryDetailResult.COMPLETE_TIME);
        id = entity.getString(QueryDetailResult.ID);
        txt_old_user.setText(username);
        int colorId = 0;
        String tradingType = "";
        if (TextUtils.equals(TradingType.PAY, type)) {
            tradingType = getString(R.string.txt_pay);
            colorId = getResources().getColor(R.color.holo_red_light);
            operate_money = "-" + operate_money;
        } else if (TextUtils.equals(TradingType.TOP_UP, type)) {
            colorId = getResources().getColor(R.color.holo_green_light);
            operate_money = "+" + operate_money;
            tradingType = getString(R.string.txt_top_up);
        }
        txt_old_type.setText(tradingType);
        txt_old_money.setText(operate_money);
        txt_old_money.setTextColor(colorId);
        txt_old_time.setText(TimerHelper.formatTime(time));

        // Calendar calendar = Calendar.getInstance();
        // int year = calendar.get(Calendar.YEAR);
        // int month = calendar.get(Calendar.MONTH);
        // int day = calendar.get(Calendar.DAY_OF_MONTH);
        // Loger.e("year--" + year + " -- month -- " + month + " -- day -- " +
        // day);
        // txt_new_time.setText(year + "年" + (month + 1) + "月" + day + "日");
        txt_new_time.setText(TimerHelper.formatTime(time));
        txt_new_type.setText(tradingType);

        txt_new_user.setText(username);

        edtxt_new_money.addTextChangedListener(mTextWatcher);

    }

    private TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null) {
                String temp = s.toString();
                if (!TextUtils.isEmpty(temp)) {
                    if (temp.contains(".")) {
                        int x = 0;
                        for (int i = 0; i <= temp.length() - 1; i++) {
                            String getstr = temp.substring(i, i + 1);
                            if (getstr.equals(".")) {
                                x++;
                                if (x == 2) {
                                    edtxt_new_money.removeTextChangedListener(this);
                                    temp = temp.substring(0, temp.length() - 1);
                                    edtxt_new_money.setText(temp);
                                    edtxt_new_money.setSelection(temp.length());
                                    edtxt_new_money.addTextChangedListener(mTextWatcher);
                                    return;
                                }
                            }
                        }
                    }
                    if (!temp.startsWith(".")) {
                        float curMoney = Float.parseFloat(temp);
                        if (curMoney >= 99999.99) {
                            curMoney = 99999.99f;
                            edtxt_new_money.removeTextChangedListener(this);
                            temp = "" + 99999.99;
                            edtxt_new_money.setText(temp);
                            edtxt_new_money.setSelection(temp.length());
                            ToastHelper.getInstance().showShortMsg("最大金额为99999.99!");
                            edtxt_new_money.addTextChangedListener(mTextWatcher);
                        } else {
                            int posDot = temp.indexOf(".");
                            if (posDot <= 0) return;
                            if (temp.length() - posDot - 1 > 2) {
                                s.delete(posDot + 3, posDot + 4);
                            }
                        }
                    } else {
                        edtxt_new_money.removeTextChangedListener(this);
                        temp = "0" + temp;
                        edtxt_new_money.setText(temp);
                        edtxt_new_money.setSelection(temp.length());
                        edtxt_new_money.addTextChangedListener(mTextWatcher);
                    }
                }
            }
        }
    };

    @OnClick(R.id.txt_new_time)
    public void txt_new_time(View view) {
        // selectTime();
    }

    private CustomDatePickerDialog mCustomDatePickerDialog;

    protected void selectTime() {
        final Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        if (mCustomDatePickerDialog == null) {
            mCustomDatePickerDialog = new CustomDatePickerDialog(ServerModifyDetailActivity.this, mOnDateSetListener,
                    year,
                    month, cal.get(Calendar.DAY_OF_MONTH));
        } else {
            mCustomDatePickerDialog.updateDate(year, month + 1, day);
        }
        isDialogOk = false;
        mCustomDatePickerDialog.setTitle(year + "年" + (month + 1) + "月" + day);
        mCustomDatePickerDialog.show();
        mCustomDatePickerDialog.setCanceledOnTouchOutside(false);
        mCustomDatePickerDialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (!isDialogOk) {
                    mCurDate = "";
                    txt_new_time.setText(getString(R.string.txt_time));
                    Loger.e("onCancel is " + mCurDate);
                }
            }
        });
        mCustomDatePickerDialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                isDialogOk = false;
            }
        });
    }

    protected boolean isDialogOk = false;
    private String mCurDate;

    private OnDateSetListener mOnDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            isDialogOk = true;
            mCurDate = year + "_" + (monthOfYear + 1) + "_" + dayOfMonth;
            Loger.e("onDateSet is " + mCurDate);
            txt_new_time.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
        }

    };

    private boolean isReset = false;

    private void editByAdmin(String id, String money, String type, String username) {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String imei = getIMEI();
        params.addBodyParameter("token", getToken());
        params.addBodyParameter("imei", imei);
        params.addBodyParameter("id", id);
        params.addBodyParameter("money", money);
        params.addBodyParameter("type", type);
        params.addBodyParameter("username", username);
        String url = ConfigProperties.SERVICE_URL + "editByAdmin.do";
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerModifyDetailActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("加载中,请等待...");
                mDialog.show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerModifyDetailActivity.this != null && !ServerModifyDetailActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo.result is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                String msg = jsonObject.getString("message");
                                if (success) {
                                    isReset = success;
                                    if (TextUtils.isEmpty(msg)) {
                                        msg = "修改成功!";
                                    }
                                    ToastHelper.getInstance().showShortMsg(msg);
                                    setResult(RESULT_OK);
                                    finish();
                                } else {
                                    new ViewHelper(ServerModifyDetailActivity.this).showBTNDialog(msg);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerModifyDetailActivity.this).showBTNDialog("加载失败,请重试!");
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Loger.e("msg:" + msg);
                if (ServerModifyDetailActivity.this != null && !ServerModifyDetailActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    new ViewHelper(ServerModifyDetailActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    @Override
    protected void titlebarMethod(int id) {

    }

    @OnClick(R.id.txt_new_user)
    public void txt_new_user(View view) {
        queryMembersByType(FROM_MODIFY_DETAIL_ACTIVITY);

    }

    @Override
    protected void parseQueryMembersByTypeResult() {
        String title = "请选择用户名";
        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                username = mUserStrs[which];
                txt_new_user.setText(mUserStrs[which]);
            }
        };
        new ViewHelper(ServerModifyDetailActivity.this).showListDialog(title, mUserStrs, clickListener);
    }

    @OnClick(R.id.txt_new_type)
    public void txt_new_type(View view) {
        String title = "请选择类型";
        final String[] items = new String[] {
                "充值", "缴费"
        };
        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                type = String.valueOf(which);
                txt_new_type.setText(items[which]);
            }
        };
        new ViewHelper(ServerModifyDetailActivity.this).showListDialog(title, items, clickListener);
    }

    @OnClick(R.id.btn_ok)
    public void btn_ok(View view) {
        if (edtxt_new_money == null || edtxt_new_money.getText() == null) {
            return;
        }
        String money = edtxt_new_money.getText().toString();
        if (TextUtils.isEmpty(money)) {
            ToastHelper.getInstance().showShortMsg("请输入金额!");
            return;
        }
        editByAdmin(id, money, type, username);
    }

    @Override
    protected void ibtn_back() {
        if (isReset) {
            setResult(RESULT_OK);
        }
        super.ibtn_back();
    }

    @Override
    public void onBackPressed() {
        if (isReset) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }
}
